/*
 * AddRemoveTokensCommand.java
 *
 * Created on 12 maj 2007, 22:33
 */

package edu.uj.petri.commands;

import edu.uj.petri.model.Place;
import edu.uj.petri.view.Canvas;
import edu.uj.petri.view.PlaceView;
import edu.uj.petri.view.View;
import java.util.ResourceBundle;

/**
 *
 * @author Piotrek
 */
public class AddRemoveTokensCommand extends Command {
    
    private int tokens;
    private Place place;
    
    /** Creates a new instance of AddRemoveTokensCommand */
    public AddRemoveTokensCommand(Place place, int howMany) {
        tokens = howMany;
        this.place = place;
    }

    public String toString() {
        StringBuffer retval = new StringBuffer();
        retval.append(ResourceBundle.getBundle("edu/uj/petri/messages").getString( (tokens >= 0) ? "adding" : "removing" ));
        int abs = (tokens>0) ? tokens : -tokens;
        retval.append(" ").append(abs).append(" ");
        retval.append(ResourceBundle.getBundle("edu/uj/petri/messages").getString( (abs == 1) ? "token" : "tokens" ));
        retval.append(" ");
        retval.append(ResourceBundle.getBundle("edu/uj/petri/messages").getString( (tokens >=0) ? "to" : "from" ));
        retval.append(" ");
        retval.append(ResourceBundle.getBundle("edu/uj/petri/messages").getString("(to)place"));
        retval.append(" ").append(place.getName());
        return retval.toString();
    }

    void execute() {
        try {
            place.addTokens(tokens);
        }
        catch (IllegalArgumentException e) {
            e.printStackTrace();  // gdy tokenow jest 0
        }
    }

    void undo() {
        place.deleteTokens(tokens);
    }

    /**
     * returns true when both commands are instances of AddRemoveTokensCommand,
     * act on the same place and either both add tokens or both remove tokens
     */
    boolean canBeCombined(Command c) {
        if( !(c instanceof AddRemoveTokensCommand) )
            return false;
        AddRemoveTokensCommand another = (AddRemoveTokensCommand)c;
        return( another.place == this.place && another.tokens * this.tokens > 0);
    }

    void combine(Command c) {
        if (!canBeCombined(c))
            throw new IllegalArgumentException(ResourceBundle.getBundle("edu/uj/petri/messages").getString("cannot_be_combined"));
        AddRemoveTokensCommand another = (AddRemoveTokensCommand)c;
        this.tokens += another.tokens;
    }
    
    private static final long serialVersionUID = 5757019210555500415L;
    
}
